package com.dragee.modules.work.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dragee.common.PageUtils;
import com.dragee.common.R;
import com.dragee.config.exception.BusinessErrorType;
import com.dragee.config.exception.BusinessException;
import com.dragee.constants.CommonConstants;
import com.dragee.modules.work.entity.*;
import com.dragee.modules.work.service.*;
import com.dragee.modules.work.vo.SaveApplyProject;
import com.dragee.modules.work.vo.SaveApplyVo;
import com.dragee.utils.LoginUserUtil;
import com.dragee.utils.UploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 报名
 *
 * @author tc
 * @email tc@mail.com
 * @date 2023-04-24 11:32:01
 */
@RestController
@RequestMapping("work/apply")
@Api(tags = "work - 报名")
public class ApplyController {
    @Autowired
    private ApplyService applyService;
    @Autowired
    private CompetitionService competitionService;
    @Autowired
    private TeamService teamService;
    @Autowired
    private CompetitionProjectService competitionProjectService;
    @Autowired
    private ApplyProjectService applyProjectService;
    @Autowired
    private TeamRefereeService teamRefereeService;
    @Autowired
    private TeamOtherService teamOtherService;
    @Autowired
    private TeamLeaderService teamLeaderService;
    @Autowired
    private TeamCoachService teamCoachService;
    @Autowired
    private TeamAthleteService teamAthleteService;
    @Value("${webull.mapUploadPath}")
    private String rootPath;

    private final String file_join_Pay = "joinPay";
    private final String file_music = "music";

    /**
     * 列表
     */
    @GetMapping("list")
    @ApiOperation("报名列表")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = applyService.queryPage(params);
        return R.ok().put("data", page);
    }

    @GetMapping("getApplyGroupsDic")
    @ApiOperation("获取这场比赛可以报名的组别Dic")
    public R getApplyGroupsDic (@RequestParam("competitionId") Long competitionId) {
        CompetitionEntity competition = competitionService.getById(competitionId);
        if (competition == null) {
            throw new BusinessException("数据异常, 当前比赛数据不存在");
        }
        String groups = competition.getGroups();
        String[] groupArr = StrUtil.isNotBlank(groups) ? groups.split(",") : new String[]{};
        return R.ok().put("data", groupArr);
    }

    @GetMapping("getApplyTypeDic")
    @ApiOperation("获取这场比赛的大类Dic")
    public R getApplyTypeDic (@RequestParam("competitionId") Long competitionId) {
        List<CompetitionProjectEntity> projects
                = competitionProjectService.getProjectByCompetition(competitionId.toString());
        List<String> collect = projects.stream().map(CompetitionProjectEntity::getType).distinct().collect(Collectors.toList());
        return R.ok().put("data", collect);
    }

    @GetMapping("getApplyProjectDic")
    @ApiOperation("获取这场比赛的项目Dic")
    public R getApplyProjectDic (@RequestParam("competitionId") Long competitionId,
                                 @RequestParam("type") String type) {
        List<CompetitionProjectEntity> projects
                = competitionProjectService.getProjectByCompetition(competitionId.toString());
        List<CompetitionProjectEntity> collect = projects.stream().filter(p -> p.getType().equals(type)).collect(Collectors.toList());
        return R.ok().put("data", collect);
    }

    /**
     * 信息
     */
    @GetMapping("{id}")
    @ApiOperation("报名信息")
    public R  info(@PathVariable("id") Long id) {
        ApplyEntity apply = applyService.getApplyInfo(id.toString());
        return R.ok().put("data", apply);
    }

    /**
     * 保存
     */
    @PostMapping("saveOrUpdate")
    @ApiOperation("保存或修改报名")
    public R saveOrUpdate(@RequestBody SaveApplyVo vo){
        CompetitionEntity competition
                = competitionService.getById(vo.getCompetitionId());
        TeamEntity team = teamService.getTeamByUserId(LoginUserUtil.getLoginUserId().toString());

        ApplyEntity old = applyService.getOne(new QueryWrapper<ApplyEntity>()
                .eq("teamId", team.getId())
                .eq("competitionId", competition.getId()), false);
        if (old != null) {
//            throw new BusinessException("您已经参与了报名，当前您的报名状态为【"+old.getStatus()+"】请勿重复报名");
            applyService.removeById(old.getId());
            applyProjectService.remove(new QueryWrapper<ApplyProjectEntity>().eq("applyId", old.getId()));
        }
        ApplyEntity apply = new ApplyEntity();
        apply.setName(vo.getName());
        apply.setTeamId(team.getId().toString());
        apply.setTitle(team.getName() + "-" + competition.getName());
        apply.setCompetitionName(competition.getName());
        apply.setCompetitionId(vo.getCompetitionId());
        apply.setLeaderIds(vo.getLeaderIds());
        apply.setCoachIds(vo.getCoachIds());
        apply.setRefereeIds(vo.getRefereeIds());
        apply.setOtherIds(vo.getOtherIds());
        apply.setSingleRoomPresonSum(vo.getSingleRoomPresonSum());
        apply.setStandardRoomPersonSum(vo.getStandardRoomPersonSum());
        apply.setStatus("草稿");
        apply.setProvince(team.getProvince());
        apply.setPinFangType(vo.getPinFangType());
        apply.setInvoiceBank(vo.getInvoiceBank());
        apply.setInvoiceBankAddress(vo.getInvoiceBankAddress());
        apply.setInvoiceTaxNumber(vo.getInvoiceTaxNumber());
        apply.setInvoiceTitle(vo.getInvoiceTitle());
        apply.setInvoiceTel(vo.getInvoiceTel());
        apply.setInvoiceEmail(vo.getInvoiceEmail());
        applyService.saveOrUpdate(apply);
        Long applyId = apply.getId();
        BigDecimal cost = new BigDecimal(0);
        // 报名费
        BigDecimal entryCost = new BigDecimal(0);
        for (SaveApplyProject p : vo.getProjects()) {
            CompetitionProjectEntity project = competitionProjectService.getById(p.getProjectId());
            ApplyProjectEntity applyProject = new ApplyProjectEntity();
            applyProject.setApplyId(applyId.toString());
            applyProject.setAthleteIds(p.getAthleteIds());
            applyProject.setType(p.getType());
            applyProject.setGroups(p.getGroups());
            applyProject.setProjectCoachIds(p.getProjectCoachIds());
            applyProject.setProjectId(p.getProjectId());
            applyProject.setCompetitionId(competition.getId().toString());
            String[] athleteArr = p.getAthleteIds().split(",");
            BigDecimal entryPrice = project.getEntryPrice() == null ? BigDecimal.ZERO : project.getEntryPrice();
            BigDecimal projectCost = entryPrice.multiply(new BigDecimal(athleteArr.length));
            entryCost = entryCost.add(projectCost);
            applyProject.setCost(entryPrice.multiply(new BigDecimal(athleteArr.length)));
            applyProjectService.saveOrUpdate(applyProject);
        }
        apply.setEntryCost(entryCost);
        cost = cost.add(entryCost);

        //  领队费用
        BigDecimal leaderCost = new BigDecimal(0);
        if (StrUtil.isNotBlank(apply.getLeaderIds())) {
            String[] arr = apply.getLeaderIds().split(",");
            leaderCost = competition.getLeaderPrice().multiply(new BigDecimal(arr.length));
        }
        apply.setLeaderCost(leaderCost);
        cost = cost.add(leaderCost);

        // 教练员费用
        BigDecimal coachCost = new BigDecimal(0);
        if (StrUtil.isNotBlank(apply.getCoachIds())) {
            String[] arr = apply.getCoachIds().split(",");
            coachCost = competition.getCoachPrice().multiply(new BigDecimal(arr.length));
        }
        apply.setCoachCost(coachCost);
        cost = cost.add(coachCost);

        // 住宿费用
        BigDecimal zhuSuCost = new BigDecimal(0);
        BigDecimal singleRoomPrice =
                new BigDecimal(apply.getSingleRoomPresonSum()).multiply(competition.getSingleRoomPrice());
        BigDecimal standardPrice =
                new BigDecimal(apply.getStandardRoomPersonSum()).multiply(competition.getStandardRoomPrice());
        zhuSuCost = singleRoomPrice.add(standardPrice);
        apply.setZhuSuCost(zhuSuCost);
        cost = cost.add(zhuSuCost);

        apply.setCost(cost);
        applyService.saveOrUpdate(apply);
        return R.ok();
    }

    public static void main(String[] args) {
        String ids = "123";
        String[] split = ids.split(",");
        System.out.println(split.length);
    }

    @GetMapping("isCanApply")
    @ApiOperation("校验是否可以报名")
    public R isCanApply (@RequestParam("completetionId") String competitionId)  {
        TeamEntity team = teamService.getTeamByUserId(LoginUserUtil.getLoginUserId() + "");
        if (team == null) {
            throw new BusinessException("当前登陆人没有单位信息");
        }
        ApplyEntity old = applyService.getOne(new QueryWrapper<ApplyEntity>()
                .eq("teamId", team.getId())
                .eq("competitionId", competitionId), false);
        if (old != null) {
            throw new BusinessException("当前比赛您已参加报名, 报名状态为【"+old.getStatus()+"】");
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @GetMapping("submitApply")
    @ApiOperation("报名提交")
    public R submitApply(@RequestParam("id") String id){
        ApplyEntity applyEntity = applyService.getById(id);
        applyEntity.setStatus("待审核");
        applyEntity.setJoinTime(new Date());
        applyService.saveOrUpdate(applyEntity);
        return R.ok();
    }

    /**
     * 删除
     */
    @GetMapping("delete-by-id")
    @ApiOperation("报名删除")
    public R delete( String id){
        deleteData(id);
		applyService.removeById(Long.parseLong(id));
        return R.ok();
    }

    @GetMapping("delete-by-ids")
    @ApiOperation("报名批量删除")
    public R deletes(String ids){
        String[] idArr = ids.split(",");
        for (String id : idArr) {
            deleteData(id);
            applyService.removeById(Long.parseLong(id));
        }
        return R.ok();
    }

    private void deleteData (String id) {
        int total = applyProjectService.count(new QueryWrapper<ApplyProjectEntity>().eq("competitionId", id));
        if (total > 0) {
            throw new BusinessException("该数据下存在报名项目,请先删除该数据");
        }
    }


    /**
     * 列表
     */
    @PostMapping("uploadMusic")
    @ApiOperation("上传音乐")
    public R uploadMusic(MultipartFile file, String id) throws Exception {
        if (file == null || id == null) {
            throw new BusinessException(BusinessErrorType.INVALID_PARAMS);
        }
        String path = rootPath + CommonConstants.PIC_DIR + "/" + LocalDateTime.now().format(DateTimeFormatter.BASIC_ISO_DATE);
        UploadUtil.uploadOne(file, path, file_music, Long.parseLong(id));
        return R.ok();
    }

    /**
     * 列表
     */
    @PostMapping("uploadPayPic")
    @ApiOperation("上传缴费凭证")
    public R uploadPayPic(MultipartFile file, String id) throws Exception {
        if (file == null || id == null) {
            throw new BusinessException(BusinessErrorType.INVALID_PARAMS);
        }
        String path = rootPath + CommonConstants.PIC_DIR + "/" + LocalDateTime.now().format(DateTimeFormatter.BASIC_ISO_DATE);
        UploadUtil.uploadOne(file, path, file_join_Pay, Long.parseLong(id));
        return R.ok();
    }




}
